import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:hc_bot_kit/hc_bot_kit.dart';
import 'package:hc_bot_kit/state.dart';

class RobotHardwareService {
  Function(GuideState)? onNavigationStateChanged;

  final hcBotKitPlugin = HcBotKit();

  final String _ipAddrssKey = "com.hc.bot.ip";
  final defaultIP = "127.0.0.1";
  //final defaultIP = "192.168.3.129";

  final String _originPoiKey = "com.hc.bot.poi.origin";

  final _box = GetStorage();

  //destination
  String _lastDestination = "";
  String get lastDestination => _lastDestination;
}

extension BotGuide on RobotHardwareService {
  Future<List<String>> getAllPoi() async {
    return hcBotKitPlugin.fetchAllPoints();
  }

  Future connect() async {
    await hcBotKitPlugin.connect(ipAddress);

    hcBotKitPlugin.stateStream?.asBroadcastStream().listen((v) {
      if (onNavigationStateChanged != null) {
        onNavigationStateChanged!(v);
      }
    });
  }

  Future guide(String dst) async {
    assert(dst.isNotEmpty);
    _lastDestination = dst;
    await hcBotKitPlugin.startGuide(dst);
  }
}

extension BotIp on RobotHardwareService {
  String get ipAddress => _box.read(_ipAddrssKey) ?? defaultIP;

  Future saveIP(String ipAddress) async {
    bool isIP = ipAddress.isIPv4 || ipAddress.isIPv6;
    if (!isIP) {
      return Future.error("Invalid IP");
    }
    await _box.write(_ipAddrssKey, ipAddress);
    await _box.save();
  }
}

extension BotOrigin on RobotHardwareService {
  String get originPoi => _box.read<String>(_originPoiKey) ?? "接待处";

  Future saveOriginPoi(String poi) async {
    await _box.write(_originPoiKey, poi);
    await _box.save();
  }
}
